package com.j4cf.lx.controller.admin;

import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.j4cf.auth.dao.entity.AuthUser;
import com.j4cf.auth.service.AuthUserService;
import com.j4cf.common.base.*;
import com.j4cf.common.util.MD5Util;
import com.j4cf.common.validator.FixedLengthValidator;
import com.j4cf.common.validator.LengthValidator;
import com.j4cf.common.validator.NotNullValidator;
import com.j4cf.lx.base.BaseController;
import com.j4cf.lx.dao.entity.LxMemberCard;
import com.j4cf.lx.dao.entity.LxMemberType;
import com.j4cf.lx.dao.dto.LxMemberDTO;
import com.j4cf.lx.service.LxMemberCardService;
import com.j4cf.lx.service.LxMemberTypeService;
import com.j4cf.lx.service.LxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Description:
 * @Author: LongRou
 * @CreateDate: 2018 2018/3/28 18:18
 * @Version: 1.0
 **/
@RestController
@RequestMapping("/admin/LxAgent")
@Api(value = "代理商控制器", description = "代理商管理")
public class LxAgentController extends BaseController{
    private static final Logger LOGGER = LoggerFactory.getLogger(LxAgentController.class);
    @Autowired
    private AuthUserService authUserService;
    @Autowired
    private LxUserService lxUserService;
    @Autowired
    private LxMemberCardService lxMemberCardService;
    @Autowired
    private LxMemberTypeService lxMemberTypeService;

    @ApiOperation(value = "查询所有代理商信息",notes = "查询所有代理商信息")
    @RequiresPermissions("lx:lxagent:read")
    @RequestMapping(value = "/selectAll" ,method = RequestMethod.GET)
    public BaseResult<List<AuthUser>> selectAll(@RequestParam Map<String, Object> params) {
        LOGGER.debug("selectAll => "+params);
        BaseQuery<AuthUser> query = new BaseQuery(params);
        try {
            return new BaseResult(BaseResultEnum.SUCCESS,lxUserService.selectAllAgentUser(query.getEntityWrapper()));
        }catch (Exception e){
            return new BaseResult(BaseResultEnum.ERROR,"请检查参数是否正确");
        }
    }

    @ApiOperation(value = "查询所有代理商信息分页",notes = "查询所有代理商信息分页")
    @RequiresPermissions("lx:lxagent:read")
    @RequestMapping(value = "/selectPage" ,method = RequestMethod.GET)
    public BaseResult<Page<AuthUser>> selectPage(@RequestParam Map<String, Object> params) {
        LOGGER.debug("selectPage => "+params);
        BaseQuery<AuthUser> query = new BaseQuery(params);
        try {
            Page<AuthUser> tPage =new Page<>(query.getPage(),query.getSize());
            tPage.setSearchCount(true);
            return new BaseResult(BaseResultEnum.SUCCESS,lxUserService.selectPageAgentUser(tPage,query.getEntityWrapper()));
        }catch (Exception e){
            return new BaseResult(BaseResultEnum.ERROR,"请检查参数是否正确");
        }
    }

    @ApiOperation(value = "新增代理商信息",notes = "新增代理商信息")
    @RequiresPermissions("lx:lxagent:add")
    @RequestMapping(value = "/insert" ,method = RequestMethod.POST ,consumes = MediaType.APPLICATION_JSON_VALUE)
    public BaseResult insert(@RequestBody AuthUser entity) {
        //信息校验
        ComplexResult result = FluentValidator.checkAll()
                .on(entity.getUsername(), new LengthValidator(5, 20, "帐号"))
                .on(entity.getPassword(), new LengthValidator(5, 32, "密码"))
                .on(entity.getRealname(), new NotNullValidator("真实姓名"))
                .on(entity.getPhone(), new FixedLengthValidator(11, "电话"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new BaseResult(BaseResultEnum.ERROR, result.getErrors().get(0).getErrorMsg());
        }
        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        entity.setSalt(salt);
        entity.setPassword(MD5Util.md5(entity.getPassword() + entity.getSalt()));
        entity.setCtime(System.currentTimeMillis());
        AuthUser authUser = authUserService.selectOne(new EntityWrapper<AuthUser>().eq("username",entity.getUsername()));
        if (null != authUser){return new BaseResult(BaseResultEnum.ERROR, "账号已存在");}
        if (lxUserService.insertAgentUser(entity)){
            return new BaseResult(BaseResultEnum.SUCCESS, "账号创建成功！");
        }else {
            return new BaseResult(BaseResultEnum.ERROR, "代理商账号创建失败！");
        }
    }

    @ApiOperation(value = "根据代理商账号重置代理商密码",notes = "根据代理商账号重置代理商密码")
    @RequiresPermissions("lx:lxagent:update")
    @RequestMapping(value = "/resetAgentUserPassword" ,method = RequestMethod.PUT ,consumes = MediaType.APPLICATION_JSON_VALUE)
    public BaseResult resetAgentUserPassword(@RequestBody AuthUser entity) {
        //信息校验
        ComplexResult result = FluentValidator.checkAll()
                .on(entity.getPassword(), new LengthValidator(5, 32, "密码"))
                .on(entity.getUsername(), new NotNullValidator("代理商账号"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new BaseResult(BaseResultEnum.ERROR, result.getErrors().get(0).getErrorMsg());
        }
        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        entity.setSalt(salt);
        entity.setPassword(MD5Util.md5(entity.getPassword() + entity.getSalt()));
        AuthUser authUser = authUserService.selectOne(new EntityWrapper<AuthUser>().eq("username",entity.getUsername()));
        if (null == authUser){return new BaseResult(BaseResultEnum.ERROR, "账号不存在");}
        authUser.setSalt(salt);
        authUser.setPassword(entity.getPassword());
        if (authUserService.updateById(authUser)){
            return new BaseResult(BaseResultEnum.SUCCESS, "密码重置成功！");
        }else {
            return new BaseResult(BaseResultEnum.ERROR, "密码重置失败！");
        }
    }

    @ApiOperation(value = "根据ID修改代理商信息", notes = "根据ID修改代理商信息")
    @RequiresPermissions("lx:lxagent:update")
    @RequestMapping(value = "/updateById" ,method = RequestMethod.PUT ,consumes = MediaType.APPLICATION_JSON_VALUE)
    public BaseResult updateById(@RequestBody AuthUser entity) {
        //信息校验
        ComplexResult result = FluentValidator.checkAll()
                .on(entity.getPhone(), new FixedLengthValidator(11, "电话号码"))
                .on(entity.getUserId()+"", new NotNullValidator("代理商编号"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new BaseResult(BaseResultEnum.ERROR, result.getErrors().get(0).getErrorMsg());
        }
        AuthUser authUser = new AuthUser();
        authUser.setUserId(entity.getUserId());
        authUser.setPhone(entity.getPhone());
        authUser.setRealname(entity.getRealname());
        authUser.setLocked(entity.getLocked());
        if (authUserService.updateById(authUser)){
            return new BaseResult(BaseResultEnum.SUCCESS, "修改成功！");
        }else {
            return new BaseResult(BaseResultEnum.ERROR, "修改失败！");
        }
    }

    @ApiOperation(value = "查询代理商下会员信息分页",notes = "查询代理商下会员信息分页")
    @RequiresPermissions("lx:lxagent-info:read")
    @RequestMapping(value = "/selectLxAgentInfoPage" ,method = RequestMethod.GET)
    public BaseResult<Page<LxMemberDTO>> selectLxAgentInfoPage(@RequestParam Map<String, Object> params) {
        //信息校验
        ComplexResult result = FluentValidator.checkAll()
                .on(params.get("agentUserId")+"", new NotNullValidator("代理商编号"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new BaseResult(BaseResultEnum.ERROR, result.getErrors().get(0).getErrorMsg());
        }
        params.put("agent_user_id",params.get("agentUserId"));
        params.remove("agentUserId");
        BaseQuery baseQuery = new BaseQuery<LxMemberCard>(params);
        try {
            Page<LxMemberCard> tPage =new Page<>(baseQuery.getPage(),baseQuery.getSize());
            tPage.setSearchCount(true);
            return new BaseResult(BaseResultEnum.SUCCESS,lxMemberCardService.selectLxMemberPage(tPage,baseQuery.getEntityWrapper()));
        }catch (Exception e){
            return new BaseResult(BaseResultEnum.ERROR,"请检查参数是否正确");
        }
    }

    @ApiOperation(value = "查询所有会员种类",notes = "查询所有会员种类")
    @RequiresPermissions("lx:lxagent-info:read")
    @RequestMapping(value = "/selectAllLxMemberType" ,method = RequestMethod.GET)
    public BaseResult<List<LxMemberType>> selectAllLxMemberType(@RequestParam Map<String, Object> params) {
        BaseQuery baseQuery = new BaseQuery<LxMemberType>(params);
        try {
            return new BaseResult(BaseResultEnum.SUCCESS,lxMemberTypeService.selectList(baseQuery.getEntityWrapper()));
        }catch (Exception e){
            return new BaseResult(BaseResultEnum.ERROR,"请检查参数是否正确");
        }
    }

    @ApiOperation(value = "为代理商添加会员额度",notes = "为代理商添加会员额度")
    @RequiresPermissions("lx:lxagent-info:add")
    @RequestMapping(value = "/addLxMemberCardForAgent" ,method = RequestMethod.POST ,consumes = MediaType.APPLICATION_JSON_VALUE)
    public BaseResult addLxMemberCardForAgent(@RequestBody Map<String, Object> params) throws Exception{
        Integer agentId = (Integer) params.get("agentId");
        Integer memberTypeId = (Integer) params.get("memberTypeId");
        Integer cardNum = (Integer) params.get("cardNum");
        Integer consumeMin = (Integer) params.get("consumeMin");
        Long otime = (Long) params.get("otime");
        Integer isFree = (Integer) params.get("isFree");
        if (cardNum<1 || consumeMin<0 || otime <0){return new BaseResult(BaseResultEnum.ERROR, "参数有误");}
        LxMemberType lxMemberType = lxMemberTypeService.selectById(memberTypeId);
        if (null == lxMemberType){return new BaseResult(BaseResultEnum.ERROR, "会员类型不存在");}

        List<LxMemberCard> lxMemberCardList = new ArrayList<>();
        LxMemberCard lxMemberCard = new LxMemberCard();
        PropertyUtils.copyProperties(lxMemberCard, lxMemberType);
        lxMemberCard.setConsumeMin(consumeMin);
        if (isFree == 1){
            lxMemberCard.setName(lxMemberCard.getName()+"(赠送)");
        }
        lxMemberCard.setCtime(System.currentTimeMillis());
        lxMemberCard.setOtime(otime);
        lxMemberCard.setState(0);
        lxMemberCard.setAgentUserId(agentId);
        for (int i = 0; i < cardNum; i++) {
            lxMemberCardList.add(lxMemberCard);
        }
        if (lxMemberCardService.insertBatch(lxMemberCardList)){
            return new BaseResult(BaseResultEnum.SUCCESS, "分配成功！");
        }else {
            return new BaseResult(BaseResultEnum.ERROR, "分配失败！");
        }
    }
}
